package com.doudou.feign;

import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @Author: 傻男人
 * @Date: 2020/5/25 11:28
 * @Version: 1.0
 * @Description: 自定义feign错误的返回
 */
@Configuration
@Slf4j
public class CustomErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        log.info("================enter custom feign error decoder ===================");
        log.info(s);
        //放出客户端异常
        if (response.status() >= 400 && response.status() <= 499) {
            String message = String.format("status %s reading %s", response.status(), s);
            try {
                if (response.body() != null) {
                    String body = Util.toString(response.body().asReader());
                    message = message + "; content:" + body;
                }
            } catch (IOException var4) {

            }
            log.info("feign 客户端异常没有被custom feign error decoder拦截，详情为:{}", message);
            return new HystrixBadRequestException(message);
        }

        return FeignException.errorStatus(s, response);
    }
}
